{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Non-decreasing Array with Single Modification\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/egtOZFrPlpWHIwyf22zynw)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "You are given an array of integers in an arbitrary order. Return whether or not it is possible to make the array non-decreasing by modifying at most 1 element to any value.\n",
    "\n",
    "> An array is non-decreasing if `array[i] <= array[i + 1]` holds for every `i` ($1 \\leq i \\lt n$)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example\n",
    "\n",
    "`[13, 4, 7]` should return `True`, since we can modify `13` to any value less than or equal to `4`, to make it non-decreasing.\n",
    "\n",
    "`[13, 4, 1]` however, should return `False`, since there is no way to modify just one element to make the array non-decreasing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def check(array: list) -> bool:\n",
    "    # Initialize the number of elements that should be modified.\n",
    "    modification = 0\n",
    "    # Traverse all elements, check if they satisfy the requirements.\n",
    "    for k in range(len(array) - 1):\n",
    "        # If they don't, mark them.\n",
    "        if array[k] > array[k + 1]:\n",
    "            modification += 1\n",
    "    # Judge with the definition.\n",
    "    return modification <= 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "print(check([13, 4, 7]))\n",
    "print(check([5, 1, 3, 2, 5]))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
